package net.cassite.daf4j.jpa;

import net.cassite.daf4j.UpdateEntry;
import net.cassite.daf4j.ds.ObjectResolver;
import net.cassite.daf4j.ds.UpdateEntryParser;
import net.cassite.daf4j.util.Location;

/**
 * 将UpdateEntry解释为JPQL
 */
public class JPQLUEParser implements UpdateEntryParser<JPQLContext, String> {
        private ObjectResolver<JPQLContext, String> objectResolver;

        @Override
        public void parseUpdateEntry(JPQLContext jpqlContext, UpdateEntry[] updateEntries) throws Exception {
                StringBuilder sb = new StringBuilder();
                sb.append("UPDATE ").append(jpqlContext.entityClass.getSimpleName()).append(" ").append(jpqlContext.aliasMap.get(new Location(null))).append(" SET ");
                boolean isFirst = true;
                for (UpdateEntry entry : updateEntries) {
                        if (isFirst) {
                                isFirst = false;
                        } else {
                                sb.append(", ");
                        }
                        sb.append(objectResolver.resolve(jpqlContext, entry.data)).append(" = ").append(objectResolver.resolve(jpqlContext, entry.updateValue));
                }
                jpqlContext.generalJPQL = sb;
        }

        @Override
        public void setObjectResolver(ObjectResolver<JPQLContext, String> objectResolver) {
                this.objectResolver = objectResolver;
        }
}
